package lib

func init() {
	Probs = append(Probs, Problem{
		Num:         289,
		Discription: "生命游戏",
		Level:       2,
		Labels: map[string]int{
			"矩阵":  1,
			"中间态": 1,
		},
	})
}

func GameOfLife(board [][]int) {
	dirs := [8][2]int{{1, 0}, {0, 1}, {-1, 0}, {0, -1}, {1, 1}, {1, -1}, {-1, 1}, {-1, -1}}
	getAlive := func(i, j int) int {
		aliveCount := 0
		for _, dir := range dirs {
			x := i + dir[0]
			y := j + dir[1]
			if x < 0 || x >= len(board) || y < 0 || y >= len(board[0]) {
				continue
			}

			if board[x][y] == 1 || board[x][y] == -1 {
				aliveCount++
			}
		}

		return aliveCount
	}

	for i := 0; i < len(board); i++ {
		for j := 0; j < len(board[0]); j++ {
			aliveNum := getAlive(i, j)
			if board[i][j] == 0 && aliveNum == 3 {
				board[i][j] = -2
			} else if board[i][j] == 1 && (aliveNum < 2 || aliveNum > 3) {
				board[i][j] = -1
			}
		}
	}

	for i := 0; i < len(board); i++ {
		for j := 0; j < len(board[0]); j++ {
			if board[i][j] == -1 {
				board[i][j] = 0
			} else if board[i][j] == -2 {
				board[i][j] = 1
			}
		}
	}
}
